<template>
  <div>
    <div class="primary">
      <el-dialog
        :title="pageEdit ? '编辑属性' : '选择属性'"
        :visible.sync="dialogVisible"
        @close="dialogVisibleClose"
        width="630px"
      >
        <!-- 编辑 -->
        <div class="content_area" v-if="pageEdit">
          <div class="list_area list_edit">
            <div v-for="(item, index) in groupListAll" :key="item.groupId" class="group_item">
              <div class="group_head">
                <span>{{ item.groupName }}</span>
                <span v-if="item.groupId" style="flex-shrink: 0">
                  <span style="cursor: pointer; color: #1c94fa" @click="handleEditGroup(item)">编辑</span>
                  <span
                    style="cursor: pointer; color: #1c94fa; margin-left: 15px; margin-right: 5px"
                    @click="handleShowTip(item, 'group', null)"
                    >删除</span
                  >
                </span>
              </div>
              <div class="group_content">
                <el-table
                  :data="item.children"
                  border
                  stripe
                  :ref="'editTable' + index"
                  style="width: 100%; margin-top: 10px"
                  max-height="180"
                  :header-cell-style="{
                    color: '#666666',
                    textAlign: 'center',
                    height: '46px',
                    backgroundColor: '#EDEDED',
                  }"
                  :cell-style="{
                    textAlign: 'center',
                    height: '44px',
                    padding: '0',
                  }"
                >
                  <el-table-column prop="no" label="序号" width="90">
                    <template slot-scope="scope">
                      <span>{{ scope.row.no + 1 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="text" label="属性值" width="180">
                    <template slot-scope="scope">
                      <!-- @keyup.native.enter="handleEditProperty(scope.row, item)" -->
                      <el-input
                        v-if="scope.row.edit"
                        v-model="scope.row.text"
                        @blur="handleSaveProperty(scope.row, item)"
                        maxlength="20"
                        :autofocus="!scope.row.id"
                        ref="editInput"
                      ></el-input>
                      <span v-else>{{ scope.row.text }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" label="操作">
                    <template slot-scope="scope">
                      <a @click="handleEditProperty(scope.row, item)">编辑</a>
                      <el-divider direction="vertical"></el-divider>
                      <a @click="handleShowTip(scope.row, 'property', item)">删除</a>
                      <el-divider direction="vertical"></el-divider>
                      <a @click="handleMoveProperty(scope.row, item, 'up')">上移</a>
                      <el-divider direction="vertical"></el-divider>
                      <a @click="handleMoveProperty(scope.row, item, 'down')">下移</a>
                      <el-divider direction="vertical"></el-divider>
                      <a @click="handleChangeGroup(scope.row, item)">改组</a>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="add_property" @click="handleAddProperty(item, index)">+添加属性值</div>
              </div>
            </div>
          </div>
          <div class="bottom_area">
            <div style="display: flex; justify-content: space-between">
              <el-button @click="handleAddGroup">添加分组</el-button>
              <el-button @click="onEditCancel">取消</el-button>
              <!-- <div>不要保存了
              <el-button type="primary">保存</el-button>
            </div> -->
            </div>
          </div>
        </div>
        <!-- 选择 -->
        <div class="content_area" v-else>
          <div style="display: flex; padding-bottom: 10px">
            <el-input
              v-model="searchValue"
              placeholder="搜索属性值"
              size="small"
              style="margin-right: 10px"
              clearable
              @keyup.native.enter="handleSearch"
            ></el-input>
            <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
          </div>
          <div class="list_area list_normal">
            <div v-for="item in groupList" :key="item.key" class="group_item">
              <div class="group_head">
                <span>{{ item.groupName }}</span>
                <span style="cursor: pointer; color: #1c94fa; flex-shrink: 0" @click="handleSelectAll(item)">全选</span>
              </div>
              <div class="group_content">
                <div
                  v-for="(child, cIndex) in item.children"
                  :key="cIndex"
                  class="property_item"
                  :class="{
                    normal: selectList.findIndex((el) => el.id == child.id) == -1,
                    active: selectList.findIndex((el) => el.id == child.id) != -1,
                  }"
                  @click="handleSelectProperty(child, item)"
                >
                  {{ child.text }}
                </div>
              </div>
            </div>
          </div>
          <div class="bottom_area">
            <div style="display: flex; justify-content: space-between">
              <el-button @click="handlePageEdit">编辑</el-button>
              <div>
                <el-button @click="dialogVisibleClose">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelect">确认选择</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
    <!-- 提醒弹框 -->
    <PopupReminder ref="reminderRef" :tipsData="tipsData" @dialogVisibleClose="onNo" @onConfirm="onYes"></PopupReminder>
    <!-- 成功弹框 -->
    <PopupSuccess ref="successRef" :tipsData="tipsData"></PopupSuccess>
    <el-dialog :title="commonTitle" :visible.sync="commonVisible" @close="commonVisible = false" width="360px">
      <div v-if="commonType == 1 || commonType == 2">
        <div style="font-size: 12px; height: 25px">请输入分组名称：</div>
        <el-input v-model="commonData.groupName" placeholder="分组名称" size="small" maxlength="20"></el-input>
      </div>
      <div v-if="commonType == 3" style="overflow: auto; max-height: 300px">
        <el-radio-group v-model="commonData.radio">
          <el-radio :label="item.groupId" v-for="item in groupList" :key="item.groupId">{{ item.groupName }}</el-radio>
        </el-radio-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <div style="width: 100%; text-align: center">
          <el-button size="small" @click="commonVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="handleCommonConfirm">保 存</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { List } from 'echarts'
import { delcommafy } from '../../utils'
import PopupReminder from './popupReminder'
import PopupSuccess from './popupSuccess'
import { getAction, putAction } from '@/api/manage'
import { deleteAction, postAction } from '../../api/manage'
export default {
  components: {
    PopupReminder,
    PopupSuccess,
  },
  props: {
    newData: Object,
  },
  created() {
    // this.getUnitList()
  },
  computed: {},
  data() {
    return {
      tipsData: {
        tipsState: '',
        tipsWords: '',
        tipsMark: '',
      },
      dialogVisible: false,
      searchValue: '',
      propertyType: 'color',
      pageEdit: false,
      commonTitle: '',
      commonType: 1,
      commonVisible: false,
      commonData: {},
      sourceList: [], //存放原始数据
      groupList: [], //选择使用
      groupListAll: [], //编辑使用
      selectList: [],

      propsParams: {},
      lockIds: []
    }
  },
  methods: {
    show(params, list) {
      this.propsParams = params
      this.selectList = []
      this.groupList = []
      this.groupListAll = []
      this.propertyType = params.type == 'color' ? 1 : 2
      this.pageEdit = false
      this.getAttributeList()
      this.dialogVisible = true
      this.selectList = list
      this.searchValue = ''
      console.log(this.selectList)
      console.log(this.propsParams)
      if (this.propsParams.doOrder == 1) {
        this.lockIds = this.propsParams.lockIds.split(',')
      } else {
        this.lockIds = []
      }
    },
    dialogVisibleClose() {
      this.dialogVisible = false
    },
    onEditCancel() {
      this.pageEdit = false
      this.getAttributeList()
    },
    handlePageEdit() {
      this.pageEdit = true
      this.groupListAll = JSON.parse(JSON.stringify(this.groupList))
    },
    handleConfirmSelect() {
      if (this.selectList.length == 0) {
        return this.$message.warning('请选择属性值')
      }
      let ids = this.selectList.map((item) => item.id).join(',')
      let text = this.selectList.map((item) => item.text).join('|')
      this.$emit('confirmSelect', {
        type: this.propertyType,
        ids: ids,
        text: text,
      })
      this.dialogVisibleClose()
    },
    handleShowTip(record, type, item) {
      this.commonData = record
      if (type == 'group') {
        this.tipsData.tipsWords = '删除后，分组下属性值的分组将置空，确认删除此分组？'
        this.tipsData.tipsMark = 'handleDelGroup'
      } else {
        let index = (item.children || []).findIndex((el) => el.edit)
        if (index > -1) return
        if (!record.id && !record.text) {
          //没保存没输入直接删除
          item.children.splice(record.no, 1)
          item.children.map((el, index) => {
            el.no = index
          })
          return
        } else if (record.text) {
          this.commonData.groupId = item.groupId
        }
        this.tipsData.tipsWords = '确定要删除此行属性吗?'
        this.tipsData.tipsMark = 'handleDelProperty'
      }
      this.$refs.reminderRef.showSmart()
    },
    // 提醒弹框确认后操作
    onYes(mark) {
      if (mark == 'handleDelProperty') {
        this.handleDelProperty()
      } else if (mark == 'handleDelGroup') {
        this.handleDelGroup()
      }
    },
    // 提醒弹框确认后操作
    onNo(mark) {},
    handleAddGroup() {
      this.commonTitle = '添加分组'
      this.commonType = 1
      this.commonData = {
        groupName: '',
      }
      this.commonVisible = true
    },
    handleEditGroup(item) {
      this.commonTitle = '编辑分组'
      this.commonType = 2
      this.commonData = {
        id: item.groupId,
        groupName: item.groupName,
        groupType: this.propertyType,
      }
      this.commonVisible = true
    },
    getAttributeList() {
      let params = {
        attributeType: this.propertyType,
      }
      getAction('/xghGoods/attribute/listByGroup', params).then((res) => {
        if (res.success) {
          console.log(res)
          let result = res.result || []
          this.sourceList = result
          this.groupList = result
          if (this.pageEdit) {
            this.groupListAll = JSON.parse(JSON.stringify(this.groupList))
          }
          result.forEach(element => {
            (element.children || []).forEach(item => {
              let index = this.selectList.findIndex(el => item.id == el.id)
              if (index > -1) {
                this.selectList[index].groupId = element.groupId
              }
            })
          });
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleSearch() {
      if (!this.searchValue) {
        this.groupList = JSON.parse(JSON.stringify(this.sourceList))
      } else {
        this.groupList = this.sourceList
          .map((item) => {
            if (item.groupName.includes(this.searchValue)) {
              return item
            } else {
              let list = item.children.filter((el) => el.text.includes(this.searchValue))
              if (list.length > 0) {
                return {
                  ...item,
                  children: list,
                }
              } else {
                return null
              }
            }
          })
          .filter((item) => item)
      }
    },
    handleCommonConfirm() {
      if (this.commonType == 1) {
        this.addGroupRequest()
      } else if (this.commonType == 2) {
        this.editGroupRequest()
      } else if (this.commonType == 3) {
        this.changeGroupRequest()
      }
    },
    addGroupRequest() {
      postAction('/xghGoods/attributeGroup/add', {
        groupName: this.commonData.groupName,
        groupType: this.propertyType,
      }).then((res) => {
        if (res.success) {
          if (res.result) {
            this.commonVisible = false
            this.getAttributeList()
            this.$message.success('分组新增成功')
          } else {
            this.$message.error('分组新增失败')
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },
    editGroupRequest() {
      postAction('/xghGoods/attributeGroup/edit', this.commonData).then((res) => {
        if (res.success) {
          this.commonVisible = false
          this.getAttributeList()
          this.$message.success('分组编辑成功')
        } else {
          this.$message.error(res.message || '分组编辑失败')
        }
      })
    },
    handleDelGroup() {
      deleteAction('/xghGoods/attributeGroup/delete', {
        id: this.commonData.groupId,
      }).then((res) => {
        if (res.success) {
          this.getAttributeList()
          this.$message.success('分组删除成功')
        } else {
          this.$message.error(res.message || '分组删除失败')
        }
      })
    },
    // 新增属性
    handleAddProperty(item, index) {
      let editIndex = (item.children || []).findIndex((el) => el.edit)
      if (editIndex > -1) return

      item.children.push({
        no: item.children.length,
        id: '',
        text: '',
        edit: true,
      })
      this.$nextTick(() => {
        const table = this.$refs['editTable' + index][0].$el.querySelector('.el-table__body-wrapper')
        if (table) {
          table.scrollTop = table.scrollHeight
        }

        const input = this.$refs.editInput[0]
        if (input) input.focus()
      })
    },
    //编辑
    handleEditProperty(record, item) {
      let index = (item.children || []).findIndex((el) => el.edit)
      if (index > -1) return
      if (!record.hasOwnProperty('edit') || !record.edit) {
        this.$set(record, 'edit', true)
        this.$nextTick(() => {
          const input = this.$refs.editInput[0]
          if (input) input.focus()
        })
      }
    },
    handleSaveProperty(record, item) {
      setTimeout(() => {
        if (record.id && !record.text) {
          return this.$message.warning('请输入属性值')
        } else if (!record.id && !record.text) {
          let index = (item.children || []).findIndex((el) => !el.id && !el.text)
          item.children.splice(index, 1)
          return this.$message.warning('属性值不能为空')
        }
        let url = 'add'
        if (record.id) {
          url = 'edit'
        }
        record.edit = false
        postAction(`/xghGoods/attribute/${url}`, {
          attributeGroupId: item.groupId,
          attributeType: this.propertyType,
          attributeValue: record.text,
          id: record.id,
        }).then((res) => {
          if (res.success) {
            console.log(res)
            this.$message.success(`属性${url == 'edit' ? '编辑' : '添加'}成功`)
            this.getAttributeList()
          } else {
            this.$message.error(res.message)
            if (record.id) {
              let text = this.sourceList.find(el => el.groupId == item.groupId).children.find(el => el.id == record.id).text
              record.text = text
            } else {
              const errIndex = (item.children || []).findIndex((el) => !el.id && el.text == record.text)
              if (errIndex > -1) item.children.splice(errIndex, 1)
            }
          }
        })
      }, 500)
    },
    handleDelProperty() {
      console.log(this.commonData)
      if (!this.commonData.id) {
        //没保存但输入有值提示后删除
        let item = this.groupListAll.find((el) => el.groupId == this.commonData.groupId)
        item.children.splice(this.commonData.no, 1)
        item.children.map((el, index) => {
          el.no = index
        })
        return
      }

      deleteAction('/xghGoods/attribute/delete', {
        id: this.commonData.id,
      }).then((res) => {
        if (res.success) {
          this.getAttributeList()
          this.$message.success(`属性删除成功`)
          let index = this.selectList.findIndex((el) => el.id == this.commonData.id)
          if (index > -1) {
            this.selectList.splice(index, 1)
          }
          this.$emit('deleteProperty', {
            type: this.propertyType,
            id: this.commonData.id,
          })
        } else {
          this.$message.error(res.message || '属性删除失败')
        }
      })
    },
    handleChangeGroup(record, item) {
      let index = (item.children || []).findIndex((el) => el.edit)
      if (index > -1) return
 
      this.commonTitle = '修改分组'
      this.commonType = 3
      this.commonData = {
        id: record.id,
        radio: item.groupId,
      }
      this.commonVisible = true
    },
    changeGroupRequest() {
      console.log(this.commonData);
      
      postAction('/xghGoods/attribute/move', {
        id: [this.commonData.id],
        attributeGroupId: this.commonData.radio || -1,
      }).then((res) => {
        if (res.success) {
          this.commonVisible = false
          this.getAttributeList()
          this.$message.success('改组成功')
        } else {
          this.$message.error(res.message || '改组失败')
        }
      })
    },
    handleMoveProperty(record, items, type) {
      let index1 = (items.children || []).findIndex((el) => el.edit)
      if (index1 > -1) return
      let item = items.children.map((el) => {
        return {
          ...el,
          sort: el.no,
        }
      })
      record.sort = record.no
      let empty = item.filter((el) => !el.id)
      if (empty.length > 0) {
        return this.$message.warning('分组内有未保存的属性，请先保存')
      }
      let index = item.findIndex((el) => el.id == record.id)
      if (index == -1) {
        return this.$message.warning('属性不存在')
      }
      if (type == 'up') {
        if (index == 0) {
          return this.$message.warning('已经是第一个')
        }
        item[index - 1].sort = index
        item[index].sort = index - 1
      } else if (type == 'down') {
        if (index == item.length - 1) {
          return this.$message.warning('已经是最后一个')
        }
        item[index + 1].sort = index
        item[index].sort = index + 1
      }
      let params = item
        .map((el) => {
          return {
            id: el.id,
            sort: el.sort,
          }
        })
        .sort((a, b) => a.sort - b.sort)
      postAction('/xghGoods/attribute/sort', params).then((res) => {
        if (res.success) {
          this.$message.success('操作成功')
          this.getAttributeList()
        } else {
          this.$message.error(res.message || '操作失败')
        }
      })
    },
    handleSelectAll(item) {
      let list = item.children
      let num = this.selectList.filter((el) => el.groupId == item.groupId).length
      // console.log('已选个数：', num);
      // console.log('全部个数：', this.contentData.length);
      if (num < list.length) {
        for (let i = 0; i < list.length; i++) {
          let index = this.selectList.findIndex((el) => el.id == list[i].id)
          if (index == -1) {
            this.selectList.push({
              ...list[i],
              groupId: item.groupId,
            })
          }
        }
      } else {
        let locks = this.selectList.filter((el) => el.groupId == item.groupId).filter((el) => this.lockIds.includes(el.id))
        console.log(locks);
        
        if (locks.length > 0) {
          this.$message.warning('已使用的属性不能取消')
        }
        this.selectList = this.selectList.filter((el) => el.groupId != item.groupId || this.lockIds.includes(el.id + ''))
      }
    },
    handleSelectProperty(child, item) {
      let index = this.selectList.findIndex((el) => el.id == child.id)
      if (index == -1) {
        this.selectList.push({
          ...child,
          groupId: item.groupId,
        })
      } else if (this.lockIds.includes(child.id + '')) {
        this.$message.warning('已使用的属性不能取消')
      } else {
        this.selectList.splice(index, 1)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.primary ::v-deep .el-dialog {
  margin-top: 8vh !important;

  .el-dialog__header {
    margin: 0 30px;
    padding: 20px 0 10px;
    border-bottom: #ededed 1px solid;
  }
}
.content_area {
  padding: 20px 30px;
  height: 82vh;
}
.group_item {
  padding: 10px 0;

  .group_head {
    color: #666666;
    font-size: 14px;
    font-family: PingFang SC-Medium;
    display: flex;
    justify-content: space-between;
  }
  .group_content {
    display: flex;
    flex-wrap: wrap;

    .property_item {
      padding: 5px 15px;
      border: #d9d9d9 1px solid;
      border-radius: 6px;
      margin: 10px 10px 0 0;
      cursor: pointer;
      flex-shrink: 0;
      &.active {
        background-color: #1890ff;
        color: white;
      }
    }
    .property_item.normal:hover {
      border-color: #1890ff;
      color: #1890ff;
    }

    ::v-deep .el-table {
      border: 1px solid #ebeef5;
    }

    ::v-deep .el-input {
      height: 32px;
      .el-input__inner {
        height: 32px;
      }
    }
  }
}
.list_area {
  overflow: auto;
  padding-bottom: 3px;
}
.list_edit {
  height: calc(100% - 50px);
}
.list_normal {
  height: calc(100% - 100px);
}
.list_area::-webkit-scrollbar {
  width: 6px;
}

.bottom_area {
  padding-top: 10px;
  border-top: #ededed 1px solid;
  margin-top: 10px;

  ::v-deep .el-button {
    padding: 8px 20px;
  }
}

.add_property {
  width: 100%;
  height: 40px;
  border: 1px dashed #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10px 0;
}
::v-deep .el-radio-group {
  display: flex;
  flex-direction: column;
  .el-radio {
    line-height: 2;
    white-space: wpre-wrap;
  }
}
</style>

